package com.beiing.tianshuai.tianshuai.adapter;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.entity.DynamicCommentAndReplyBean;
import com.beiing.tianshuai.tianshuai.util.EmotionUtils;
import com.qmuiteam.qmui.span.QMUITouchableSpan;
import com.qmuiteam.qmui.widget.textview.QMUISpanTouchFixTextView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by LZQ on 2017/11/28.
 */

public class DynamicListComment_RVAdapter extends RecyclerView.Adapter<DynamicListComment_RVAdapter.mViewHolder> {

    private Context context;
    private List<DynamicCommentAndReplyBean> mData;
    private LayoutInflater layoutInflater;
    private OnItemClickListener mOnItemClickListener;
    private OnNameClickListener mOnNameClickListener;

    DynamicListComment_RVAdapter(Context context, List<DynamicCommentAndReplyBean> commentAndReplyBeans) {
        this.context = context;
        this.mData = commentAndReplyBeans;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public mViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.item_comment_reply, parent, false);
        return new mViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final mViewHolder holder, int position) {
        if (mData.get(position).getTable_type().equals("0") || mData.get(position).getTable_type().equals("1")) {
            //字符串拼接
            SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
            String name = mData.get(position).getF_name();
            stringBuilder.append(TextUtils.isEmpty(name) ? "" : name);
            stringBuilder.append("：");
            String contentCode = null;
            try {
                contentCode = URLDecoder.decode(mData.get(position).getContent(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (contentCode != null){
                stringBuilder.append(contentCode.trim());
            }

            //表情拼接
            Resources res = context.getResources();
            String regexEmotion = "\\[([\u4e00-\u9fa5\\w+\\.])+\\]";
            Pattern patternEmotion = Pattern.compile(regexEmotion);
            Matcher matcherEmotion = patternEmotion.matcher(stringBuilder);
            while (matcherEmotion.find()) {
                // 获取匹配到的具体字符
                String key = matcherEmotion.group();
                // 匹配字符串的开始位置
                int start = matcherEmotion.start();
                // 利用表情名字获取到对应的图片
                Integer imgRes = EmotionUtils.getImgByName(key);
                // 压缩表情图片
                int size = (int) holder.mTextView.getTextSize() * 13 / 10;
                if (imgRes != -1){
                    Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
                    Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);

                    ImageSpan span = new ImageSpan(context, scaleBitmap);
                    stringBuilder.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }

            holder.itemView.setTag(position);

            //评论人点击事件
            if (!TextUtils.isEmpty(name)) {
                //设置高亮颜色
                int nameLength = name.length();
                stringBuilder.setSpan(new QMUITouchableSpan(
                        Color.parseColor("#67A0FF"),
                        Color.parseColor("#67A0FF"),
                        Color.parseColor("#00000000"),
                        Color.parseColor("#E0E0E0")) {
                    @Override
                    public void onSpanClick(View view) {
                        if (mOnNameClickListener != null) {
                            mOnNameClickListener.onNameClick(view, holder.getAdapterPosition(),
                                    0, mData.get(holder.getAdapterPosition()));
                        }
                    }
                }, 0, nameLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
            holder.mTextView.setMovementMethodDefault();
            holder.mTextView.setText(stringBuilder);
        } else if (mData.get(position).getTable_type().equals("2") || mData.get(position).getTable_type().equals("3")) {
            SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
            String fName = mData.get(position).getF_name();
            String tName = mData.get(position).getT_name();
            int fNameLength = fName.length();
            int tNameLength = tName.length();
            stringBuilder.append(fName);
            stringBuilder.append("回复");
            stringBuilder.append(tName);
            stringBuilder.append(": ");
            String contentCode = null;
            try {
                contentCode = URLDecoder.decode(mData.get(position).getContent(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (contentCode != null){
                stringBuilder.append(contentCode.trim());
            }

            //表情拼接
            Resources res = context.getResources();
            String regexEmotion = "\\[([\u4e00-\u9fa5\\w+\\.])+\\]";
            Pattern patternEmotion = Pattern.compile(regexEmotion);
            Matcher matcherEmotion = patternEmotion.matcher(stringBuilder);
            while (matcherEmotion.find()) {
                // 获取匹配到的具体字符
                String key = matcherEmotion.group();
                // 匹配字符串的开始位置
                int start = matcherEmotion.start();
                // 利用表情名字获取到对应的图片
                Integer imgRes = EmotionUtils.getImgByName(key);
                // 压缩表情图片
                int size = (int) holder.mTextView.getTextSize() * 13 / 10;
                if (imgRes != -1){
                    Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
                    Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);

                    ImageSpan span = new ImageSpan(context, scaleBitmap);
                    stringBuilder.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }

            //回复人名字点击事件
            stringBuilder.setSpan(new QMUITouchableSpan(
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#00000000"),
                    Color.parseColor("#E0E0E0")) {
                @Override
                public void onSpanClick(View view) {
                    if (mOnNameClickListener != null) {
                        mOnNameClickListener.onNameClick(view, holder.getAdapterPosition(),
                                0, mData.get(holder.getAdapterPosition()));
                    }
                }
            }, 0, fNameLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            //被回复人名字点击事件
            stringBuilder.setSpan(new QMUITouchableSpan(
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#00000000"),
                    Color.parseColor("#E0E0E0")) {
                @Override
                public void onSpanClick(View view) {
                    if (mOnNameClickListener != null) {
                        mOnNameClickListener.onNameClick(view, holder.getAdapterPosition(),
                                1, mData.get(holder.getAdapterPosition()));
                    }
                }
            }, fNameLength + 2, fNameLength + 2 + tNameLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            holder.mTextView.setMovementMethodDefault();
            holder.mTextView.setText(stringBuilder);
        }

        holder.mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(view, holder.getAdapterPosition(),
                            mData.get(holder.getAdapterPosition()));
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        if (mData.isEmpty()) {
            return 0;
        } else {
            return mData.size();
        }
    }

    class mViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_reply)
        QMUISpanTouchFixTextView mTextView;

        public mViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position, DynamicCommentAndReplyBean commentAndReplyBean);
    }

    void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public interface OnNameClickListener {
        void onNameClick(View view, int position, int text_position, DynamicCommentAndReplyBean commentAndReplyBean);
    }

    void setOnNameClickListener(OnNameClickListener listener) {
        this.mOnNameClickListener = listener;
    }
}
